<template>
  <div class="employees">
    <el-card class="top">
      <HeTip>
        <template #right>
          <!--
            需求：
            1：点击导入跳转到一个新的上传excel页面
              a:创建新页面所对应组件
              b:配置路由
              c:完成新页面的布局
            2：点击上传选择excel读取excel文件数据并调用接口实现批量员工新增
            3：新增成功跳转到员工页面
           -->
          <el-button type="primary" size="small" @click="goputClick">
            导出
          </el-button>
          <el-button
            type="primary"
            size="small"
            @click="importClick"
          >导入</el-button>
          <el-button
            type="primary"
            size="small"
            @click="clickShow"
          >+新增员工</el-button>
        </template>
      </HeTip>
    </el-card>

    <el-card class="table">
      <el-table :data="list">
        <el-table-column label="序号" width="60px">
          <template v-slot="{ $index }">
            <div>{{ (page.page - 1) * page.size + $index + 1 }}</div>
          </template>
        </el-table-column>
        <el-table-column label="头像" sortable prop="staffPhoto" width="80px">
          <template v-slot="{ row }">
            <img
              v-imgerror
              class="avator"
              :src="row.staffPhoto"
              alt=""
              @click="imgClick(row.staffPhoto)"
            >
          </template>
        </el-table-column>
        <el-table-column label="姓名" sortable prop="username" width="130px" />
        <el-table-column label="手机号" sortable prop="mobile" />
        <el-table-column label="工号" sortable prop="workNumber" />
        <!-- <el-table-column label="聘用形式" sortable prop="formOfEmployment"> -->

        <!-- 1.使用过滤器解决 -->
        <!-- <template v-slot="{ row }">
            <div>
              {{ row.formOfEmployment | formatStr }}
            </div>
          </template> -->
        <!-- </el-table-column> -->
        <!-- <el-table-column
          :formatter="formatterForm"
          label="聘用形式"
          sortable
          prop="formOfEmployment"
        /> -->

        <!-- 2.自定义指令解决 -->
        <!-- <el-table-column label="聘用形式" sortable prop="formOfEmployment">
          <template v-slot="{ row }">
            <div v-directiveForm="row.formOfEmployment">
              {{ row.formOfEmployment }}
            </div>
          </template></el-table-column> -->

        <!-- 3.数据源头解决 -->
        <el-table-column label="聘用形式" sortable prop="formOfEmployment2" />
        <el-table-column label="部门" sortable prop="departmentName" />
        <el-table-column label="入职时间" sortable prop="timeOfEntry2" />
        <el-table-column label="是否在职" sortable prop="enableState2" />
        <el-table-column label="操作" width="300px" fixed="right">
          <template v-slot="{ row }">
            <div>
              <el-button type="text" @click="togo(row.id)">查看</el-button>
              <el-button type="text">转正</el-button>
              <el-button type="text">调岗</el-button>
              <el-button type="text">离职</el-button>
              <el-button
                type="text"
                @click="setRulesClick(row.id)"
              >角色</el-button>
              <!--
                v-BtnControl.inlineBlock="'employees_delBtn'"
                 v-BtnControl： 使用自定义指令用于处理按钮的权限
               -->
              <el-button
                v-BtnControl.inlineBlock="'employees_delBtn'"
                type="text"
                @click="del(row.id)"
              >删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="page">
        <el-pagination
          :current-page="page.page"
          :page-sizes="[1, 5, 10, 100, 200, 300, 400]"
          :page-size="page.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增弹框组件 -->
    <!-- <Add :is-show="show" @update:isShow="show = $event" /> -->
    <Add :is-show.sync="show" @getData="getData" />
    <el-dialog :visible.sync="imgShow" title="二维码生成">
      <div style="text-align: center">
        <canvas ref="canvas" />
      </div>
    </el-dialog>
    <!-- 角色弹框组件 -->
    <SetRules ref="setRules" />
  </div>
</template>

<script>
import { sysUser, sysUserDelete } from '@/api/employees.js'
import employeesObj from '@/api/constant/employees.js'
import Add from '@/views/employees/components/add.vue'
import moment from 'moment'
import { export_json_to_excel } from '@/vendor/Export2Excel'
// import employees from '@/api/constant/employees.js'
import Qrcode from 'qrcode'
import SetRules from './components/setRules.vue'
export default {
  // filters: {
  //   formatStr(id) {
  //     // 找到id匹配的项
  //     // 返回值=数组.find(item=>{return boolean值，true，返回=当前项的item，} 如果所有项都是false，返回值是undefined)
  //     const temp = employeesObj.hireType.find((item) => {
  //       return item.id === id
  //     })
  //     // 返回该项的value数据
  //     return temp ? temp.value : '--'
  //   }
  // },
  components: {
    Add,
    SetRules
  },
  data() {
    return {
      list: [{}],
      imgShow: false, // 头像二维码是否显示
      show: false, // 是否显示新增弹框
      page: {
        page: 1, //	1	页码
        size: +localStorage.getItem('employessSize') || 10, //  初始化数据时获取页容量数据
        total: 100
      }
    }
  },
  created() {
    this.getData()
  },
  methods: {
    async getData() {
      const res = await sysUser(this.page)
      // 数据源头进行转换
      res.data.rows.forEach((item) => {
        item.formOfEmployment2 = this.formatterForm(
          null,
          null,
          item.formOfEmployment
        )
        // 转换是否在职
        item.enableState2 = this.findState(item.enableState)
        item.timeOfEntry2 = moment(item.timeOfEntry).format('YYYY-MM-DD')
      })
      this.list = res.data.rows
      // 存储total
      this.page.total = res.data.total
      console.log(res)
    },
    // 转换是否在职
    findState(id) {
      const result = employeesObj.workingState.find((item) => {
        return +item.id === id
      })
      return result ? result.value : '--'
    },
    handleSizeChange(size) {
      this.page.size = size
      // 页容量修改回到第一页
      this.page.page = 1
      this.getData()
      // 页容量修改时存储到浏览器中
      localStorage.setItem('employessSize', size)
    },
    handleCurrentChange(page) {
      this.page.page = page
      // 页码与页容量修改时都调用接口
      this.getData()
    },
    // 聘用 形式转换
    formatterForm(row, column, cellValue, index) {
      // findIndex: 返回值=数组.findIndex(item=>{return Boolean true,返回值是当前项的索引} 所有项都是false, 返回值是-1)
      const _index = employeesObj.hireType.findIndex((item) => {
        return item.id === cellValue
      })
      return _index === -1 ? '--' : employeesObj.hireType[_index].value
    },
    // 点击新增按钮
    clickShow() {
      this.show = true
    },
    // 点击删除按钮
    del(id) {
      this.$confirm('你确定要删除嘛?', '温馨提示')
        .then(async() => {
          await sysUserDelete(id)
          this.$message.success('删除成功')
          // 刷新列表数据时注意回到第一页
          this.page.page = 1
          this.getData()
        })
        .catch(() => {})
    },
    // 点击导入按钮
    importClick() {
      this.$router.push('/employees/import')
    },
    // 点击导出按钮
    async goputClick() {
      // 获取所有员工的列表数据
      const res = await sysUser({
        page: 1,
        size: 10000
      })
      // console.log('所有员工数据', res)
      /*
      correctionTime: "2018-11-30"
      departmentName: "总裁办"
      enableState: 1
      formOfEmployment: 1
      id: "604f764971f93f3ac8f365c2"
      mobile: "13800000002"
      password: "e10adc3949ba59abbe56e057f20f883e"
      staffPhoto: "http://q6cu3t6jv.bkt.clouddn.com/1063705989926227968?t=1616204161907"
      timeOfEntry: "2018-11-02"
      username: "管理员"
      workNumber: "9002"
      */
      const rules = {
        姓名: 'username',
        手机号: 'mobile',
        工号: 'workNumber',
        聘用形式: 'formOfEmployment',
        部门: 'departmentName',
        入职时间: 'timeOfEntry'
      }
      // 获取表头
      const header = Object.keys(rules)
      // 进行数据转换
      const data = res.data.rows.map((item) => {
        const arrNew = []
        Object.values(rules).forEach((item2) => {
          if (item2 === 'timeOfEntry') {
            arrNew.push(moment(item[item2]).format('YYYY-MM-DD'))
          } else if (item2 === 'formOfEmployment') {
            arrNew.push(this.formatterForm(null, null, item[item2]))
          } else {
            arrNew.push(item[item2])
          }
        })
        return arrNew
      })
      // 调用导出方法
      export_json_to_excel({
        header: header,
        data: data,
        filename: '文件导出'
      })
    },
    // 点击查看按钮
    togo(id) {
      // this.$router.push('/employees/detail?id=' + id)
      this.$router.push('/employees/detail/' + id)
    },
    // 点击头像生成二维码
    imgClick(imgStr) {
      // 头像不存在就不生成
      if (!imgStr) {
        return
      }
      // 打开弹框：dialog在第一次弹框后才开始渲染它的内容
      this.imgShow = true
      // 等到弹框打开后才开始渲染二维码
      this.$nextTick(() => {
        Qrcode.toCanvas(this.$refs.canvas, imgStr, {
          width: 300,
          height: 300
        })
      })
    },
    // 角色点击事件
    setRulesClick(id) {
      // 通过访问子组件实例对象来打开弹框
      this.$refs.setRules.isShow = true
      // 调用方法获取当前点击用户的角色信息
      this.$refs.setRules.getRoleIds(id)
    }
  }
}
</script>

<style lang="scss" scoped>
.employees {
  padding: 20px;
  ::v-deep .top .el-card__body {
    padding: 5px;
  }
  .table {
    margin-top: 20px;
  }
  .page {
    text-align: right;
    margin-top: 20px;
  }
  .avator {
    width: 50px;
    height: 50px;
    object-fit: contain;
  }
}
</style>
